package common.WxProgram;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: yc
 * @description: 发送小程序订阅消息
 * @author: daiyuanbao
 * @create: 2021-03-26 10:02
 */
@Component
public class SendWxMessage {


    public static String push(String openid,String page,String appId,String AppSecret,String templateId,WxMsgDto wxMsgDto,Integer num) {
        RestTemplate restTemplate = new RestTemplate();
        //这里简单起见我们每次都获取最新的access_token（时间开发中，应该在access_token快过期时再重新获取）
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + getAccessToken(openid,appId,AppSecret);
        //拼接推送的模版
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(openid);//用户的openid（要发送给那个用户，通常这里应该动态传进来的）
        wxMssVo.setTemplate_id(templateId);//订阅消息模板id
        if(StringUtils.isNotEmpty(page)){
            wxMssVo.setPage(page);
        }
        //发送消息模板数据
        setTemplateData(wxMssVo,wxMsgDto,num);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, wxMssVo, String.class);
        System.out.println("小程序推送结果={}"+ responseEntity.getBody());
        return responseEntity.getBody();
    }


    public static String getAccessToken(String openId,String appId,String AppSecret) {
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> params = new HashMap<>();
        params.put("APPID", appId);
        params.put("APPSECRET", AppSecret);  //
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}", String.class, params);
        String body = responseEntity.getBody();
        JSONObject object = JSON.parseObject(body);
        String Access_Token = object.getString("access_token");
        String expires_in = object.getString("expires_in");
        System.out.println("有效时长expires_in：" + expires_in);
        return Access_Token;
    }

    public static void setTemplateData(WxMssVo wxMssVo,WxMsgDto wxMsgDto,Integer num){
        Map<String, TemplateData> m = new HashMap<>();
        m.put(wxMsgDto.getKey1(), new TemplateData(wxMsgDto.getValue1()));
        m.put(wxMsgDto.getKey2(), new TemplateData(wxMsgDto.getValue2()));
        m.put(wxMsgDto.getKey3(), new TemplateData(wxMsgDto.getValue3()));
        if(num>=4){
            m.put(wxMsgDto.getKey4(), new TemplateData(wxMsgDto.getValue4()));
        }
        if(num==5) {
            m.put(wxMsgDto.getKey5(), new TemplateData(wxMsgDto.getValue5()));
        }
        wxMssVo.setData(m);
    }
}
